<template>
  <div class="login-container">
    <video
      class="video"
      src="../../assets/video/bg_video.mp4"
      preload="auto"
      loop="loop"
      autoplay="true"
      muted
    ></video>
    <div class="bg2"></div>
    <!-- 常规登录 -->
    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="login-loginForm"
    >
      <h1 class="title">用户管理系统</h1>
      <i
        @click="isErweiLogin = !isErweiLogin"
        :class="[
          'jiaobiao',
          'iconfont',
          isErweiLogin ? 'icon-diannaojiaobiao' : 'icon-erweimajiaobiao',
        ]"
      ></i>
      <div class="commonLogin" v-if="!isErweiLogin">
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="captcha">
          <el-input
            type="text"
            v-model="loginForm.captcha"
            class="captcha"
            ref="captcha"
            @keydown.native.enter="submitForm('loginForm')"
            autocomplete="off"
          ></el-input>
          <span
            class="captcha-svg"
            v-html="captchaSvg"
            @click="updateCaptcha"
          ></span>
        </el-form-item>

        <el-form-item>
          <el-button
            class="submit"
            type="primary"
            @click="submitForm('loginForm')"
            >提交</el-button
          >
        </el-form-item>
      </div>
      <!-- 切换二维码登录 -->
      <div class="erwei" v-else>
        <div class="img">
          <img :src="qrDataUrl" width="200px" alt="" />
          <i
            class="mask"
            v-show="isScanCodeSuccess"
            :style="qrStyle"
            @click="getQrcode"
          ></i>
        </div>
        <p class="erweitext">请用微信扫码登录</p>
      </div>
    </el-form>
  </div>
</template>
<script>
//引入api中的方法
import * as api from "../../api";
import { mapMutations } from "vuex";
//引入socket.io
import io from "socket.io-client";
//引入生成二维码的插件qrcode
import qrcode from "qrcode";
//引入扫码成功和失效的图片
import codeSuccessImg from "../../assets/imgs/scancode.png";
import codeInvalidImg from "../../assets/imgs/invalidQr.png";

var validateCaptcha = (rule, value, callback) => {
  //callback只要传参，表示表单验证不通过，不传表示表单验证通过
  //value就是input中的输入值
  //rule是个对象，就是验证对象
  if (value.length !== 5) {
    callback("验证码必须是5位");
  } else {
    callback();
  }
};
var validateUsername = (rule, value, callback) => {
  //callback只要传参，表示表单验证不通过，不传表示表单验证通过
  //value就是input中的输入值
  //rule是个对象，就是验证对象
  var reg = /^\w{3,12}$/;
  if (reg.test(value)) {
    callback();
  } else {
    callback("用户名可以是字母数字下换线，3-12位");
  }
};
var validatePass = (rule, value, callback) => {
  //callback只要传参，表示表单验证不通过，不传表示表单验证通过
  //value就是input中的输入值
  //rule是个对象，就是验证对象
  if (value.length < 3) {
    callback("密码长度不能小于3位");
  } else {
    callback();
  }
};
export default {
  data() {
    return {
      isErweiLogin: false, //是否二维码登录
      captchaSvg: "", //验证码svg
      loginForm: {
        //登录输入框的数据
        username: "",
        password: "",
        captcha: "",
      },
      rules: {
        //表单验证规则
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
      qrDataUrl: "", //二维码base64的图片地址
      isScanCodeSuccess: false, //是否显示遮罩
      qrStyle: {
        backgroundImage: `url(${codeSuccessImg})`,
      },
    };
  },
  created() {
    // console.log(process.env.VUE_APP_BASE_URL);
    this.updateCaptcha();
  },
  methods: {
    ...mapMutations(["SET_USER_INFO"]),
    // 封装一个获取二维码地址的方法
    getQrcode() {
      // 关掉qrCode的遮罩
      this.isScanCodeSuccess = false;
      // 让遮罩的样式初始化
      this.qrStyle.backgroundImage = `url(${codeSuccessImg})`;
      //从本地取出sid
      let sid = localStorage.getItem("qf-sid");
      if (!sid) {
        this.$message.error("没有sid");
        return;
      }
      api.getQrcodeUrlApi(sid).then((res) => {
        // console.log(res);
        let qrUrl = res.data.scanCodeUrl;
        //3.通过qrcode将二维码地址生成二维码
        qrcode.toDataURL(qrUrl, (err, dataUrl) => {
          // console.log(dataUrl);
          // console.log(123);
          this.isScanCodeSuccess = false; // 关掉qrcode的遮罩
          this.qrDataUrl = dataUrl;
        });
      });
    },
    //封装一个方法，专门用于获取验证码
    updateCaptcha() {
      api.getCaptchaApi().then((res) => {
        // console.log(res.data);
        this.captchaSvg = res.data.img;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        //所有的表单校验通过之后，valid的值是true
        //否则valid的值为false

        //1.先校验本地表单是否通过
        //2.校验验证码是否正确
        //3.校验用户名密码是否正确
        if (valid) {
          //打开loading动画
          const loading = this.$loading({
            lock: true,
            text: "正在登录",
            spinner: "iconfont icon-wsmp-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          //表单校验通过
          //校验验证码
          api
            .verifyCaptcha(this.loginForm.captcha.toLowerCase())
            .then((res) => {
              // console.log(res);
              if (res.data.state) {
                //验证码通过
                //继续验证用户名和密码
                api
                  .loginApi(this.loginForm.username, this.loginForm.password)
                  .then((res) => {
                    // console.log(res.data);
                    if (res.data.state) {
                      loading.close(); //关闭加载动画
                      //登录成功
                      this.$message.success({
                        message: "登录成功,正在跳转",
                        type: "success",
                        duration: 800,
                      });
                      //1,将token存到本地
                      localStorage.setItem("qf-token", res.data.token);
                      //2,将userInfo存到本地
                      localStorage.setItem(
                        "qf-userInfo",
                        JSON.stringify(res.data.userInfo)
                      );
                      //按钮权限
                      localStorage.setItem("permissionButtons",JSON.stringify(res.data.permission.buttons))
                      //3,/将用户信息添加到vuex
                      this.SET_USER_INFO(res.data.userInfo);
                      //4,跳转到主页
                      this.$router.push("/");
                    } else {
                      //登录失败，用户名或密码错误
                      // alert("用户名或密码错误");
                      this.$message.error("用户名或密码错误");
                      loading.close(); //关闭加载动画
                    }
                  });
              } else {
                // console.log("验证码错误");
                loading.close(); //关闭加载动画
                this.$message.error("验证码错误");
                //清空验证码输入框
                this.loginForm.captcha = "";
                //让输入框获得焦点
                this.$refs.captcha.focus();
                //刷新验证码
                this.updateCaptcha();
              }
            });
        } else {
          //表单校验不通过
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  watch: {
    //监听切换二维码登录的字段
    isErweiLogin(newVal, oldVal) {
      // console.log(oldVal);
      if (newVal) {
        //已经切换成了二维码登录
        //1.通过socket.io和服务器简历socket连接
        let socket = io("wss://chst.vip");
        //2.监听socket连接成功事件，发送请求，请求"/user/getScancode"获取二维码地址
        socket.on("connectSuccess", (data) => {
          // console.log(data);
          //将sid存到本地
          let { sid } = data;
          localStorage.setItem("qf-sid", sid);
          //3.获取二维码地址，并且生成二维码图片
          this.getQrcode();
        });

        //4.用户扫描二维码
        //5.监听socket事件 scancodeSuccess(这个事件不是socket.io定义的，是前后端约定的)，获取到wechatcode
        socket.on("scancodeSuccess", (data) => {
          // console.log('扫码成功');
          // console.log(data);
          //6.请求users/wechatLogin,传递wechatCode
          if (data.state) {
            //扫码成功
            //显示遮罩
            this.isScanCodeSuccess = true;
            api.wechatLoginApi(data.wechatCode).then((res) => {
              if (res.data.state) {
                // console.log(res);
                //1,将token存到本地
                localStorage.setItem("qf-token", res.data.token);
                //2,将userInfo存到本地
                localStorage.setItem(
                  "qf-userInfo",
                  JSON.stringify(res.data.userInfo)
                );
                //3,/将用户信息添加到vuex
                this.SET_USER_INFO(res.data.userInfo);
                //按钮权限
                localStorage.setItem("permissionButtons",JSON.stringify(res.data.permission.buttons))
                //4.跳转到首页
                this.$router.push("/");
              } else {
                //登录失败
                this.$message.error("微信登录失败");
              }
            });
          } else {
            //提示扫码失败
            this.$message.error("扫码失败");
          }
        });
        //7.判断成功或失败

        // 二维码失效
        socket.on("invalidCode", (data) => {
          console.log(data);
          this.qrStyle.backgroundImage = `url(${codeInvalidImg})`; //显示二维码失效的标志

          this.isScanCodeSuccess = true; //显示遮罩
        });
      } else {
        //切换成普通登录
        //二维码遮罩关闭
        this.isScanCodeSuccess = true;
      }
    },
  },
};
</script>
<style scoped lang="less">
.login-container {
  //二维码样式
  .erwei .img {
    text-align: center;
    padding-left: 80px;
    position: relative;
    height: ;

    /deep/.mask {
      width: 50%;
      height: 98%;
      opacity: 0.8;
      background-color: #fff;
      position: absolute;
      right: 15%;
      background-image: url("../../assets/imgs/scancode.png");
      background-size: 50%;
      background-repeat: no-repeat;
      background-position: center;
      cursor: pointer;
    }
    img {
      height: 200px;
    }
  }
  .erweitext {
    text-align: right;
    padding-right: 21%;
    color: #fff;
    font: "" 20px/20px;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 191px;
  }

  .jiaobiao {
    font-size: 60px;
    color: #fff;
    position: absolute;
    right: 0;
    top: -1px;
    cursor: pointer;
    opacity: 0.7;
  }
  .video {
    position: fixed;
  }
  .bg2 {
    background-image: url("../../assets/imgs/bg2.png");
    background-repeat: no-repeat;
    position: fixed;
    background-size: 50%;
    opacity: 0.7;
    background-position: 60% 65%;
    width: 50%;
    height: 100%;
  }
  .el-form {
    position: fixed;
    left: 65%;
    top: 20%;
    border-radius: 8px;
    padding-right: 80px;
    width: 400px;
    background-color: rgba(0, 0, 0, 0.3);
    padding-top: 80px;
    /deep/.el-input__inner {
      height: 45px;
    }
    .captcha {
      width: 130px;
      vertical-align: top;

      & /deep/ .el-input__inner {
        width: 100%;
        height: 45px;
        border-radius: 5px 0 0 5px;
        border: 0;
        font-size: 18px;
      }
    }
    svg path {
      stroke: red;
    }
    .captcha-svg {
      background: #fff;
      display: inline-block;
      height: 45px;
      width: 170px;
      text-align: center;
      cursor: pointer;
      border: 0;
      border-radius: 0px 5px 5px 0;
    }
    .el-button {
      width: 100%;
      background: linear-gradient(90deg, #1596fb, #002dff);
      margin-bottom: 160px;
    }
    /deep/.el-form-item__label {
      color: #fff;
    }
  }
}
.title {
  margin: 50px 0 50px 70px;
  text-align: center;
  color: #fff;
}
</style>
